//上传多媒体文件
var express = require('express');

express().use(express.static('public'));//开放访问权限

var router = express.Router();
const multer = require('multer')//头像上传插件
const fs =require('fs');//文件操作插件
const HeadImgupload = multer( { dest: '../back_blog/public/images' } )	//头像存储路径

const query = require('../bd/query')//数据库处理函数

/**
 * 上传头像
 */
router.post('/media/setheading',HeadImgupload.any(),function(req, res, next) {
    // console.log(req)
    var headimg=req.files//获得到照片
    var loginId = req.body.loginId//获得用户id
    var loginPassword = req.body.loginPassword//获得用户密码
    // console.log("账号："+loginId+"密码："+loginPassword)
    // console.log(headimg);
    var newFileName = Date.now()+headimg[0].originalname//新图片名字
    var oldFile = headimg[0].destination+'/'+headimg[0].filename
    var newFile = headimg[0].destination+'/'+newFileName//存放路径+新名字
    fs.rename(oldFile,newFile,(err)=>{
        if(err){
            res.send(JSON.stringify({statue:"no",msg:"上传失败"}))
        }
        else{
            var headImgSql = `update user set headImg = "${newFileName}" 
                                where loginId=${loginId} and loginPassword="${loginPassword}"` //修改头像的sql语句
            query(headImgSql)
            .then((result) => {
                console.log(result)
            }).catch((err) => {
                console.log(err)
            });
            // res.end(JSON.stringify({statue:"ok",msg:"上传成功"}))
        }
    })

    res.end("在制作")
});


/**
 * 头像下载
 */
router.get('/media/getHeadimg',multer({dest:'../public/headImg/'}).any(),(req,res)=>{
    var url = req.params.url
    // res.download()
});


//获取图片
router.get('/media/images', function (req, res) {
    var url=__dirname.replace(/\\/g,"/");//路径符号替换
    var img=req.query.img//或得到图片名称
    let data = fs.readFileSync(url+"/../public/images/"+ img,"binary")//获得图片
    res.writeHead(200, "Ok");//设置头
    res.write(data,"binary"); //输出图片，格式必须为 binary，否则会出错
    res.end();
})



router.post('/media/artImg',function(req,res,next){
    console.log(req)
    var headimg=req.files//获得到照片
    var newFileName = Date.now()+headimg[0].originalname//新图片名字
    var oldFile = headimg[0].destination+'/'+headimg[0].filename
    var newFile = headimg[0].destination+'/'+newFileName//存放路径+新名字
    fs.rename(oldFile,newFile,(err)=>{
        if(err){
            res.send(JSON.stringify({statue:"no",msg:"上传失败"}))
        }
        else{
            res.send("http://localhost:3003/api/media/images?img="+newFileName)
            // res.end(JSON.stringify({statue:"ok",msg:"上传成功"}))
        }
    })
})
module.exports = router;
